package cn.jekun.web.shop.action;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.DIdentifyType;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.McMemberLevel;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.DIdentifyTypeService;
import cn.jekun.component.core.service.gen.McMemberLevelService;
import cn.jekun.component.core.service.gen.McMemberService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.web.shop.bean.Order;
import cn.jekun.web.shop.bean.Shop;
import cn.jekun.web.shop.bean.ShopMember;
import cn.jekun.web.shop.service.MemberService;
import cn.jekun.web.shop.service.OrderService;


/**
 * 会员信息查询
 * 
 * @author Mr.Dong
 *
 */
@SuppressWarnings("serial")
public class MemberAction extends ShopBaseAction {
	private static final String AUTH_SHOP_MY_SECURITY="SHOP_MY_SECURITY";//安全设置

	private String memberId; 
	private String mobile;
	private String username;
	private String realname;
	private String beginCredits;
	private String endCredits;
	public String getBeginCredits() {
		return beginCredits;
	}
	public void setBeginCredits(String beginCredits) {
		this.beginCredits = beginCredits;
	}
	public String getEndCredits() {
		return endCredits;
	}
	public void setEndCredits(String endCredits) {
		this.endCredits = endCredits;
	}
	public String getRealname() {
		return realname;
	}
	public void setRealname(String realname) {
		this.realname = realname;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getMemberId() {
		return memberId;
	}
	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	private String memberType;  
	public String getMemberType() {
		return memberType;
	}
	public void setMemberType(String memberType) {
		this.memberType = memberType;
	}

	private String beginDate; 
	private String endDate; 

	public String getBeginDate() {
		return beginDate;
	}
	public void setBeginDate(String beginDate) {
		this.beginDate = beginDate;
	}
	public String getEndDate() {
		return endDate;
	}
	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}
	private List<McMemberLevel> mcMemberLevels = new ArrayList<McMemberLevel>();
	public List<McMemberLevel> getMcMemberLevels() {
		return mcMemberLevels;
	}
	public void setMcMemberLevels(List<McMemberLevel> mcMemberLevels) {
		this.mcMemberLevels = mcMemberLevels;
	}

	private List<DIdentifyType> IdentifyTypeList = new ArrayList<DIdentifyType>();
	public List<DIdentifyType> getIdentifyTypeList() {
		return IdentifyTypeList;
	}
	public void setIdentifyTypeList(List<DIdentifyType> identifyTypeList) {
		IdentifyTypeList = identifyTypeList;
	}

	private ShopMember mcMember;

	public ShopMember getMcMember() {
		return mcMember;
	}
	public void setMcMember(ShopMember mcMember) {
		this.mcMember = mcMember;
	}
	private RsUser rsUser;

	public RsUser getRsUser() {
		return rsUser;
	}
	public void setRsUser(RsUser rsUser) {
		this.rsUser = rsUser;
	}

	@Resource(name = OrderService.BEAN_NAME)
	protected OrderService orderService;
	@Resource(name=MemberService.BEAN_NAME)
	MemberService memberService;
	@Resource(name=McMemberService.BEAN_NAME)
	McMemberService mcMemberService;
	@Resource(name=DIdentifyTypeService.BEAN_NAME)
	DIdentifyTypeService identifyTypeService;
	@Resource(name=McMemberLevelService.BEAN_NAME)
	McMemberLevelService memberLevelService;
	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService rsUserService;

	@SuppressWarnings("unchecked")
	public String getShopMember(){
//		formMap.put("memberType", memberType);
//		formMap.put("memberId", memberId);
//		formMap.put("mobile", mobile);
//		formMap.put("username", username);
//		formMap.put("realname", realname);
//		formMap.put("beginDate",beginDate);
//		formMap.put("endDate",endDate);
//		formMap.put("beginCredits", beginCredits);
//		formMap.put("endCredits", endCredits);
//		formMap.put("shopId", this.getSessionUser().getShopId());
//		//判断是否有操作权限
//		this.checkRight(AUTH_SHOP_MY_SECURITY);
//		try {
//			this.resultList = this.memberService.getShopMembers(formMap,page);
//			this.mcMemberLevels = memberLevelService.list(null);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return "/shop/memberquery.jsp";
		
		
		
		JSONObject jsonObject=new JSONObject();
		try {
//			formMap.put("memberType", memberType);
//			formMap.put("memberId", memberId);
//			formMap.put("mobile", mobile);
//			formMap.put("username", username);
//			formMap.put("realname", realname);
//			formMap.put("beginDate",beginDate);
//			formMap.put("endDate",endDate);
//			formMap.put("beginCredits", beginCredits);
//			formMap.put("endCredits", endCredits);
//			formMap.put("shopId", this.getSessionUser().getShopId());
			//判断是否有操作权限
			//this.checkRight(AUTH_SHOP_MY_SECURITY);
//			try {
//				this.resultList = this.memberService.getShopMembers(formMap,page);
//				this.mcMemberLevels = memberLevelService.list(null);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			
			
			
			String shopId=this.getSessionUser().getShopId();
			String source = request.getParameter("source");
			
			this.resultList = this.memberService.getShopMembers(memberType,memberId,mobile,username,realname,
					beginDate,endDate,beginCredits,endCredits,shopId,source,page);

			JSONArray jsonArray=new JSONArray();

			HashMap<String, Object> hashMap;
			
			for(int i=0;i<this.resultList.size();i++){

				ShopMember tempShopMember=(ShopMember) resultList.get(i);
				
				hashMap=new HashMap<String, Object>();
				
				hashMap.put(ShopMember.COL_USER_ID,tempShopMember.getUserId()==null?"":tempShopMember.getUserId());
				
				hashMap.put(ShopMember.COL_CREATE_TIME,tempShopMember.getCreateTime()==null?"":DateToString(tempShopMember.getCreateTime()));
				
				hashMap.put(ShopMember.COL_USER_NAME,tempShopMember.getUserName()==null?"":tempShopMember.getUserName());

				hashMap.put(ShopMember.COL_REAL_NAME,tempShopMember.getRealName()==null?"":tempShopMember.getRealName());

				hashMap.put(ShopMember.COL_SEX,tempShopMember.getSex()==null?"":tempShopMember.getSex());
				
				hashMap.put("LEVEL_NAME",tempShopMember.getLevelName()==null?"":tempShopMember.getLevelName());
				
				hashMap.put("CREDITS",tempShopMember.getCredits()==null?"0":tempShopMember.getCredits());

				hashMap.put(ShopMember.COL_MOBILE,tempShopMember.getMobile()==null?"":tempShopMember.getMobile());

				jsonArray.add(hashMap);
				
			}
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

			jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
			
			jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
			
			jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
			
			jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
						
			jsonObject.put("memberListData", jsonArray);
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		System.err.println("josnObject = " + jsonObject);
		return this.writeJson(jsonObject);
		
		
		

	}

	
	/**
	 * 获得会员等级列表
	 * @return
	 */
	public String getMemberLevel(){
		
		JSONObject jsonObject=new JSONObject();
		try {
			this.mcMemberLevels = memberLevelService.list(null);

			JSONArray jsonArray=new JSONArray();

			HashMap<String, Object> hashMap;

			for(int i=0;i<this.mcMemberLevels.size();i++){

				McMemberLevel tempMcMemberLevel=mcMemberLevels.get(i);
				
				hashMap=new HashMap<String, Object>();
				
				hashMap.put(McMemberLevel.COL_LEVEL_ID,tempMcMemberLevel.getLevelId()==null?"":tempMcMemberLevel.getLevelId());
				
				hashMap.put(McMemberLevel.COL_LEVEL_NAME,tempMcMemberLevel.getLevelName()==null?"":tempMcMemberLevel.getLevelName());
				
				jsonArray.add(hashMap);

				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

				jsonObject.put("memberLevelListData", jsonArray);

			}
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
		
	}
	
	
	
	public String getIdentifyType(){

		this.IdentifyTypeList = this.identifyTypeService.list(null);
		this.mcMemberLevels = memberLevelService.list(null);
		return "/shop/addmemberusers.jsp";

	}

	/**
	 * 增加会员
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String addMcmember(){
//		RsUser rsUser = new RsUser();
//		rsUser.setUserName(request.getParameter("userName"));
//		rsUser.setPassword(request.getParameter("password"));
//		rsUser.setIdentifyTypeId(request.getParameter("identifyTypeId"));
//		rsUser.setIdentity(request.getParameter("identity"));
//		rsUser.setCard(request.getParameter("card"));
//		rsUser.setEmail(request.getParameter("email"));
//		rsUser.setMobile(request.getParameter("mobile"));
//		rsUser.setPhoneNumber(request.getParameter("phoneNumber"));
//		rsUser.setRealName(request.getParameter("realName"));
//		rsUser.setAddress(request.getParameter("address"));
//		rsUser.setSex(request.getParameter("sex"));
//		rsUser.setShopId(this.getSessionUser().getShopId());
//		McMember mcMember = new McMember();
//		mcMember.setLevelId(request.getParameter("memberlevel"));
//		mcMember.setShopId(this.getSessionUser().getShopId());
//		mcMember.setMemoName(request.getParameter("memoName"));
//		mcMember.setLevelId(request.getParameter("memberType"));
//		mcMember.setMemberTypeId("2");
//		mcMember.setCredits(0.0);
//		formMap.put("mcMember", mcMember);
//		formMap.put("rsUser", rsUser);
//		if(memberService.isexistsUser(request.getParameter("userName"))){
//			this.saveActionError("操作失败，已存在相同用户账号:"+request.getParameter("userName"));
//		}
//		else if(memberService.isexistsMobile(request.getParameter("mobile"))){
//			this.saveActionError("操作失败，已存在相同手机号码:"+request.getParameter("mobile"));
//		}
//		else if(!"".equals(request.getParameter("email"))
//				&& memberService.isexistsEmail(request.getParameter("email"))){
//			this.saveActionError("操作失败，已存在相同邮件地址:"+request.getParameter("email"));
//		}else{
//			if(memberService.addMember(formMap)){
//				this.saveActionMessage("增加会员成功，会员名称:"+request.getParameter("realName"));
//			}else{
//				this.saveActionError("增加会员失败，可能已存在该会员，会员名称:"+request.getParameter("realName"));
//			}
//		}
//		return "/shop/Member/getIdentifyType.do";
		
		
		
		JSONObject jsonObject=new JSONObject();

		try {
			
			String userName=request.getParameter("userName");
			String password= request.getParameter("password");
			String identifyTypeId=request.getParameter("identifyTypeId");
			String identity=request.getParameter("identity");
			String card=request.getParameter("card");
			String email=request.getParameter("email");
			String mobile=request.getParameter("mobile");
			String phoneNumber=request.getParameter("phoneNumber");
			String realName=request.getParameter("realName");
			String address=request.getParameter("address");
			String sex=request.getParameter("sex");
			String shopId=this.getSessionUser().getShopId();
			
			String memberlevel=request.getParameter("memberlevel");
			String memoName=request.getParameter("memoName");
			String memberType=request.getParameter("memberType");
			String memberTypeId="2";
			String credits="0.0";
			
			if(memberService.isexistsUser(request.getParameter("userName"))){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"操作失败，已存在相同用户账号:"+request.getParameter("userName"));
			}
			else if(memberService.isexistsMobile(request.getParameter("mobile"))){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"操作失败，已存在相同手机号码:"+request.getParameter("mobile"));
			}
			else if(!"".equals(request.getParameter("email"))&& memberService.isexistsEmail(request.getParameter("email"))){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"操作失败，已存在相同邮件地址:"+request.getParameter("email"));
			}else{
								
				memberService.addMember(userName,password,identifyTypeId,identity,card,email,mobile,phoneNumber,realName,address,sex,shopId,memberlevel,memoName,memberType);
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
				
				this.logService.addAdminAuditLog("", "新增用户资料成功，用户名称:"+userName);//记录操作日志
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"新增用户失败");
			
		}
		
		return this.writeJson(jsonObject);
		
	}
	/**
	 * 获取提现流水详情
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getAccountDetailsById(){

		Map map = new HashMap();
		map.put("accountJourId", request.getParameter("accountJourId"));
		//this.shopAccounts = accountService.getAccountDetailsById(map);

		return "/shop/accounttrandetails.jsp";
	}


	/**
	 * 会员详情
	 * @return
	 */
	public String getMemberDetails(){

//		//判断是否有操作权限
//		this.checkRight(AUTH_SHOP_MY_SECURITY);
//		try {
//			this.mcMember = this.memberService.getMemberDetails(request.getParameter("userId")
//					,this.getSessionUser().getShopId());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		if(StringUtils.isNotBlank(request.getParameter("opertype")) && 
//				"edit".equals(request.getParameter("opertype"))){
//			return "/shop/memberInfo.jsp";
//		}
//		return "/shop/memberdetail.jsp";
		
		JSONObject jsonObject=new JSONObject();
		
	
		try {
			
			String userId=request.getParameter("userId");
			
			this.mcMember = this.memberService.getMemberDetails(userId,this.getSessionUser().getShopId());
			
			if(mcMember!=null){
				
				jsonObject.put(McMember.COL_MEMBER_ID, mcMember.getMemberId()==null?"":mcMember.getMemberId());
				jsonObject.put("USER_NAME", mcMember.getUserName()==null?"":mcMember.getUserName());
				jsonObject.put("SEX", mcMember.getSex()==null?"":mcMember.getSex());
				jsonObject.put("EMAIL", mcMember.getEmail()==null?"":mcMember.getEmail());
				jsonObject.put("PHONE_NUMBER", mcMember.getPhoneNumber()==null?"":mcMember.getPhoneNumber());
				jsonObject.put("MOBILE", mcMember.getMobile()==null?"":mcMember.getMobile());
				jsonObject.put("ADDRESS", mcMember.getAddress()==null?"":mcMember.getAddress());
				jsonObject.put("CARD", mcMember.getCard()==null?"":mcMember.getCard());
				jsonObject.put("BIRTHDAY", mcMember.getBirthday()==null?"":DateToString(mcMember.getBirthday()));
				jsonObject.put("CREDITS", mcMember.getCredits()==null?"":mcMember.getCredits());
				jsonObject.put("REAL_NAME", mcMember.getRealName()==null?"":mcMember.getRealName());
				jsonObject.put("LEVEL_NAME", mcMember.getLevelName()==null?"":mcMember.getLevelName());
				jsonObject.put("MEMO_NAME", mcMember.getMemoName()==null?"":mcMember.getMemoName());
			}
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE, "调用成功");
		}catch(Exception e){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE, "获取会员详情失败");
			
		}
		return this.writeJson(jsonObject);
	}

	/**
	 * 营销短信发送
	 * @return
	 */
	public String sendMarkeSms(){
		try {
			String smsContent = request.getParameter("smsContent");
			this.memberService.sendMarkeSms(this.getSessionUser().getShopId(),smsContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/shop/sendmarkesms.jsp";	
	}

	/**
	 * 修改会员信息
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String editMemberById(){

//		try {
//			formMap.put("rsUser", rsUser);
//			formMap.put(RsUser.COL_USER_ID,request.getParameter("userId"));
//			SqlUtis.prepareSql(formMap
//					, SqlUtis.getSQLRequired(formMap,RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ)
//					);
//
//			int cnt = rsUserService.update(formMap);
//			if(cnt==1){
//				this.saveActionMessage("修改会员信息成功，会员名称:"+rsUser.getRealName());
//			}else{
//				this.saveActionError("修改会员信息失败。");
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			this.saveActionError("修改会员资料失败，邮件地址或手机号码重复！");
//		}
//		return "/shop/Member/getMemberDetails.do";
		
		
		
		/*String userId=request.getParameter("userId");
		String sex=request.getParameter("sex");
		String card=request.getParameter("card");
		String phoneNumber=request.getParameter("phoneNumber");
		String email=request.getParameter("email");
		String address=request.getParameter("address");
		String birthday=request.getParameter("birthday");*/
		String mobile=request.getParameter("mobile");
		String realName=request.getParameter("realName");
		String memberId = request.getParameter("memberId");
		String memoName = request.getParameter("memoName");
		JSONObject jsonObject=new JSONObject();
		try {
			if(StringUtils.isBlank(memberId)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"会员代码不能为空");
			}
			McMember member = new McMember();
			member.setMemberId(memberId);
			if(StringUtils.isNotBlank(memoName)){
				member.setMemoName(memoName);
			}
			int cnt = this.mcMemberService.update(member);
			if(cnt==1){
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"修改会员资料成功");
				
				this.logService.addAdminAuditLog("", "修改会员信息成功，会员名称:"+realName);//记录操作日志
			}else{
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"修改会员资料失败");
			}
				
		} catch (Exception e) {
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"修改用户失败，手机号码或邮箱地址已存在，手机号码:"+mobile);

		}		
		return this.writeJson(jsonObject);
	}
	
	
	
	
	/**
	 * 订单列表
	 * @return
	 */
	/*@SuppressWarnings("unchecked")
	public String getMyOrders(){
		
		JSONObject jsonObject=new JSONObject();
		try {
			
			if(StringUtils.isNotBlank(request.getParameter("userId"))){
				formMap.put("userId",request.getParameter("userId"));
				request.getSession().setAttribute("flag", request.getParameter("userId"));
				this.mcMember = this.memberService.getMemberDetails(request.getParameter("userId")
						,this.getSessionUser().getShopId());
			}
			List<Order> myorders = this.orderService.getMyOrders(formMap,page);

			JSONArray jsonArray=new JSONArray();

			HashMap<String, Object> hashMap;

			for(int i=0;i<myorders.size();i++){

				hashMap=new HashMap<String, Object>();
				hashMap.put("OrderId", myorders.get(i).getOrderId());
				hashMap.put("OrderTypeName", myorders.get(i).getOrderTypeName()==null?"":myorders.get(i).getOrderTypeName());
				hashMap.put("BusinessName", myorders.get(i).getBusinessName()==null?"":myorders.get(i).getBusinessName());
				hashMap.put("PayMentName", myorders.get(i).getPayMentName()==null?"":myorders.get(i).getPayMentName());
				hashMap.put("OrderStatusName", myorders.get(i).getOrderStatusName()==null?"":myorders.get(i).getOrderStatusName());
				hashMap.put("TotalAmount", myorders.get(i).getTotalAmount()==null?"":myorders.get(i).getTotalAmount());
				hashMap.put("Nums", myorders.get(i).getNums()==null?"":myorders.get(i).getNums());
				hashMap.put("Point", myorders.get(i).getPoint()==null?"":myorders.get(i).getPoint());
				hashMap.put("OrderTime", myorders.get(i).getOrderTime()==null?"":DateToDString(myorders.get(i).getOrderTime()));
				jsonArray.add(hashMap);

				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

				jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
				
				jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
				
				jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
				
				jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
							
				jsonObject.put("orderListData", jsonArray);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	
	
	*/
	
	

}
